

package mydailyline

import (
    "appengine"
    "appengine/datastore"
    "appengine/user"
    //"fmt"
    "http"
    "strings"
    "template"
    "time"
)

var (
	homeTemplate = template.MustParseFile("home.html", nil)
)

type Greeting struct {
    Author  string
    Content string
    Date    datastore.Time
    DateEntered string
    Today string
}

func init() {
    http.HandleFunc("/", root)
    http.HandleFunc("/Today", today)
    http.HandleFunc("/post", post)
    http.HandleFunc("/signout", signout)
}

func root(w http.ResponseWriter, r *http.Request) {
	//fmt.Fprint(w, "My Daily Line.\n")
	homeTemplate.Execute(w, nil)
}

func signout(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url, err := user.LogoutURL(c, "/")
	if err != nil {
            http.Error(w, err.String(), http.StatusInternalServerError)
            return
        }
    w.Header().Set("Location", url)
    w.WriteHeader(http.StatusFound)
    return

}


func today(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    
    //fmt.Fprint(w, "My Daily Line.\n")
    u := user.Current(c)
    if u == nil {
    	
        url, err := user.LoginURL(c, r.URL.String())
        if err != nil {
            http.Error(w, err.String(), http.StatusInternalServerError)
            return
        }
        w.Header().Set("Location", url)
        w.WriteHeader(http.StatusFound)
        return
    }
    
    
    
    //q := datastore.NewQuery("Greeting").Order("-Date").Limit(10)   DateEntered
    q := datastore.NewQuery("Greeting").Filter("Author =",u.String()).Order("-DateEntered").Limit(10)
    greetings := make([]Greeting, 0, 10)
    if _, err := q.GetAll(c, &greetings); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }
    if err := guestbookTemplate.Execute(w, greetings); err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
    }
}

var guestbookTemplate = template.MustParse(guestbookTemplateHTML, nil)

//const guestbookTemplateHTML = `
var guestbookTemplateHTML = `
<html>
  <body>
  Save a memory for Today: 
  <form action="/post" method="post">
      <div><input type="date" value="` + strings.Split(time.LocalTime().Format(time.RFC3339), "T",-1)[0]  +`" name="date"></div>
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Save"></div>
    </form>
    
    {.repeated section @}
      {.section Author}
        <p>On {DateEntered|html} <b>{@|html}</b> wrote:</p>
      {.or}
        <p>On {DateEntered|html} an anonymous person wrote:</p>
      {.end}
      <pre>{Content|html}</pre>
    {.end}
    <a href='/signout'>Sign Out</a>
  </body>
</html>
`

func post(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    g := Greeting{
        Content: r.FormValue("content"),
        Date:    datastore.SecondsToTime(time.Seconds()),
        DateEntered: r.FormValue("date"),
    }
    if u := user.Current(c); u != nil {
        g.Author = u.String()
    }
    
    
    
    _, err := datastore.Put(c, datastore.NewIncompleteKey("Greeting"), &g)
    if err != nil {
        http.Error(w, err.String(), http.StatusInternalServerError)
        return
    }
    http.Redirect(w, r, "/Today", http.StatusFound)
}